package cn.innosmart.aq.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.YAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.HistorySwitchListAdapter;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.bean.SwitchHistoryData;
import cn.innosmart.aq.chart.MyMarkerView;
import cn.innosmart.aq.customize.AutoRadioGroup;
import cn.innosmart.aq.customize.HorizonSimpleSelector;
import cn.innosmart.aq.customize.calendar.DateUtil;
import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2015/8/12.
 */
public class DeviceHistoryDataChartsActivity extends BaseActivity implements INetworkInteractUtil, OnChartGestureListener, OnChartValueSelectedListener {
    private final int THIRTYMINUTE = 0;
    private final int SIXHOURE = 34;
    private final int ONEDAY = 68;
    private final int ONEWEEK = 100;
    private final int EXIT = 0;
    private final int LOADINGSTART = 1;
    private final int LOADINGOVER = 2;
    private final int SWITCHLOADINGOVER = 3;
    private final int PULLUPOVER = 4;
    public int currentPosition = 0;
    private NetworkInteractUtil interactUtil;
    //    private SeekBar seekbarTimeChooser;
    private LineChart lineChart;
    private DeviceBean deviceBean = null;
    private float minValue;
    private float maxValue;
    private String uid;
    private LinearLayout llOthers;
    private HistorySwitchListAdapter historySwitchListAdapter;
    private ListView logListView;
    private LinearLayout llSwitch;
    private MyMarkerView mv;
    private AutoRadioGroup rgChoose;
    private RadioButton rbMin;
    private RadioButton rbHour;
    private RadioButton rbDay;
    private RadioButton rbWeek;

    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    private boolean isPayed = true;
    private ArrayList<SwitchHistoryData> switchHistoryDatas;
    private String day = "7d";
    private Menu menus;
    private String start;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXIT:
                    exit();
                    break;
                case LOADINGSTART:
                    //开始加载
                    loadingDialog();
                    break;
                case LOADINGOVER:
                    //结束加载
                    hideloadingDialog();
                    if (lineChart != null) {
                        lineChart.invalidate();
                    }
                    break;
                case SWITCHLOADINGOVER:
                    //刷新数据
                    historySwitchListAdapter.refreshData(switchHistoryDatas);
                    if (switchHistoryDatas.size() == 0) {
                        TextView text = (TextView) logListView.getEmptyView();
                        Date date = new Date(Long.valueOf(start));
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        text.setText(simpleDateFormat.format(date) + " " + getString(R.string.no_history_data));
                    }
                    hideloadingDialog();
                    break;
                case PULLUPOVER:
                    //付费限制
//                    showToast(getString(R.string.activity_history_unpayed_limit));
                    break;
            }
        }
    };
    private String end;
    private int type = 0;
    private int num = 0;
    private double oldValue;
    private String sum = "1m";
    private HorizonSimpleSelector modeSelectior;
    private RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb_min:
                    //选择30min
                    currentPosition = 0;
                    initialData(0);
                    break;
                case R.id.rb_hour:
                    //选择6h
                    currentPosition = 1;
                    initialData(1);
                    break;
                case R.id.rb_day:
                    //选择1d
                    currentPosition = 2;
                    initialData(2);
                    break;
                case R.id.rb_week:
                    //选择1w
                    currentPosition = 3;
                    initialData(3);
                    break;
            }
        }
    };

    /**
     * 初始化时间切换控件
     */
    private void assignViews() {
        lineChart = (LineChart) findViewById(R.id.line_chart);
        modeSelectior = (HorizonSimpleSelector) findViewById(R.id.hs_change);
        modeSelectior.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("position=" + position + "currentPosition=" + currentPosition);
                if (position == 1) {
                    //往前
                    switch (deviceBean.getFunctype()) {
                        case DeviceConstant.FUNCTYPE_SWITCH:
                        case DeviceConstant.FUNCTYPE_WATERLEVER:
                        case DeviceConstant.FUNCTYPE_FEEDER:
                            if (caculateTime(1, num)) {
                                if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
                                    interactUtil.getSwitchHistoryData(deviceBean.getDeviceid(), uid, start, end);
                                } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
                                    interactUtil.getWaterLeverHistoryData(deviceBean.getDeviceid(), uid, start, end);
                                } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER) {
                                    interactUtil.getFeederHistoryData(deviceBean.getDeviceid(), uid, start, end);
                                }
                            }
                            if (num == 0) {
                                showToast(getString(R.string.the_latest));
                            }
                            break;
                        default:
                            if (num == 0) {
                                showToast(getString(R.string.the_latest));
                                break;
                            }
                            if (caculatePeriodTime(1, num)) {
                                SimpleDateFormat 格式 = new SimpleDateFormat("M月d日 H时m分", Locale.CHINA);
                                System.out.println("当前PeriodTimeStart时间:" + 格式.format(Long.valueOf(start)));
                                System.out.println("当前PeriodTimeEnd时间:" + 格式.format(Long.valueOf(end)));
                                modeSelectior.setText(格式.format(Long.valueOf(start)), 格式.format(Long.valueOf(end)));
                            }
                            if (currentPosition == 0)
                                interactUtil.getOtherHistoryData(deviceBean.getDeviceid(), uid, String.valueOf(start), end, sum);
                            else
                                interactUtil.getOtherHistoryData(deviceBean.getDeviceid(), uid, start, end, sum);
                            break;
                    }
                } else if (position == -1) {
                    //往后
                    switch (deviceBean.getFunctype()) {
                        case DeviceConstant.FUNCTYPE_SWITCH:
                        case DeviceConstant.FUNCTYPE_WATERLEVER:
                        case DeviceConstant.FUNCTYPE_FEEDER:
                            if (caculateTime(-1, num)) {
                                if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
                                    interactUtil.getSwitchHistoryData(deviceBean.getDeviceid(), uid, start, end);
                                } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
                                    interactUtil.getWaterLeverHistoryData(deviceBean.getDeviceid(), uid, start, end);
                                } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER) {
                                    interactUtil.getFeederHistoryData(deviceBean.getDeviceid(), uid, start, end);
                                }
                            }
                            break;
                        default:
                            if (caculatePeriodTime(-1, num)) {
                                SimpleDateFormat 格式 = new SimpleDateFormat("M月d日 H时m分", Locale.CHINA);
                                System.out.println("当前PeriodTimeStart时间:" + 格式.format(Long.valueOf(start)));
                                System.out.println("当前PeriodTimeEnd时间:" + 格式.format(Long.valueOf(end)));
                                modeSelectior.setText(格式.format(Long.valueOf(start)), 格式.format(Long.valueOf(end)));
                            }
                            if (currentPosition == 0)
                                interactUtil.getOtherHistoryData(deviceBean.getDeviceid(), uid, String.valueOf(Long.valueOf(start) - 30 * 60 * 1000), end, sum);
                            else
                                interactUtil.getOtherHistoryData(deviceBean.getDeviceid(), uid, start, end, sum);
                            break;
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        rgChoose.setOnCheckedChangeListener(onCheckedChangeListener);
    }

    /**
     * 计算StartTime和EndTime时间
     *
     * @param type
     * @param number
     * @return
     */
    public boolean caculatePeriodTime(int type, int number) {
        if (type == -1) {
            num = number - 1;
        } else if (type == 1) {
            if (num >= 0) {
                return false;
            }
            num = number + 1;
        }
        System.out.println("num=" + num);
        if (num == 0) {
            initialData(currentPosition);
        } else {
            long startLong = Long.valueOf(start);
            switch (currentPosition) {
                case 0:
                    //30min
                    end = type == -1 ? new String(start) : String.valueOf(startLong + 2 * 30 * 60 * 1000);
                    start = String.valueOf(startLong + type * 30 * 60 * 1000);
                    break;
                case 1:
                    //6h
                    end = type == -1 ? new String(start) : String.valueOf(startLong + 2 * 6 * 60 * 60 * 1000);
                    start = String.valueOf(startLong + type * 6 * 60 * 60 * 1000);
                    break;
                case 2:
                    //1d
                    end = type == -1 ? new String(start) : String.valueOf(startLong + 2 * 24 * 60 * 60 * 1000);
                    start = String.valueOf(startLong + type * 24 * 60 * 60 * 1000);
                    break;
                case 3:
                    //1w
                    end = type == -1 ? new String(start) : String.valueOf(startLong + 2 * 7 * 24 * 60 * 60 * 1000);
                    start = String.valueOf(startLong + type * 7 * 24 * 60 * 60 * 1000);
                    break;
            }
        }
        return true;
    }

    /**
     * 计算Start和End
     *
     * @param type   -1 往前 +1 往后
     * @param number
     * @return
     */
    public boolean caculateTime(int type, int number) {
        if (type == -1) {
            num = number - 1;
        } else if (type == 1) {
            if (num >= 0) {
                return false;
            }
            num = number + 1;
        }
        System.out.println("num=" + num);
        if (num == 0) {
            end = String.valueOf(System.currentTimeMillis());
            start = String.valueOf(DateUtil.getTimesmorning());
        } else {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, num);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.MILLISECOND, 0);
            start = String.valueOf(cal.getTimeInMillis());
            cal.set(Calendar.HOUR_OF_DAY, 24);
            end = String.valueOf(cal.getTimeInMillis());
        }
        System.out.println("startTime=" + start + ",endTime=" + end);
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_chart);
        Intent intent = getIntent();
        deviceBean = intent.getParcelableExtra("device");
        uid = intent.getStringExtra("uid");
        interactUtil = new NetworkInteractUtil(this);
        setBar();
        llSwitch = (LinearLayout) findViewById(R.id.ll_switch);
        logListView = (ListView) findViewById(R.id.log_listView);
        logListView.setSelector(android.R.color.transparent);
        llOthers = (LinearLayout) findViewById(R.id.ll_others);
        rgChoose = (AutoRadioGroup) findViewById(R.id.rg_choose);
        //根据不同的Device显示不同的UI界面
        if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
            llSwitch.setVisibility(View.VISIBLE);
            llOthers.setVisibility(View.GONE);
            mHandler.sendEmptyMessage(LOADINGSTART);
            caculateTime(0, 0);
            //获取插座数据
            interactUtil.getSwitchHistoryData(deviceBean.getDeviceid(), uid, start, end);
            historySwitchListAdapter = new HistorySwitchListAdapter(deviceBean, this);
            logListView.setAdapter(historySwitchListAdapter);
            logListView.setEmptyView(findViewById(R.id.myText));
        } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
            llSwitch.setVisibility(View.VISIBLE);
            llOthers.setVisibility(View.GONE);
            mHandler.sendEmptyMessage(LOADINGSTART);
            caculateTime(0, 0);
            //获取水位数据
            interactUtil.getWaterLeverHistoryData(deviceBean.getDeviceid(), uid, start, end);
            historySwitchListAdapter = new HistorySwitchListAdapter(deviceBean, this);
            logListView.setAdapter(historySwitchListAdapter);
            logListView.setEmptyView(findViewById(R.id.myText));
        } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER) {
            llSwitch.setVisibility(View.VISIBLE);
            llOthers.setVisibility(View.GONE);
            mHandler.sendEmptyMessage(LOADINGSTART);
            caculateTime(0, 0);
            //获取喂食数据
            interactUtil.getFeederHistoryData(deviceBean.getDeviceid(), uid, start, end);
            historySwitchListAdapter = new HistorySwitchListAdapter(deviceBean, this);
            logListView.setAdapter(historySwitchListAdapter);
            logListView.setEmptyView(findViewById(R.id.myText));
        } else {
            llSwitch.setVisibility(View.GONE);
            llOthers.setVisibility(View.VISIBLE);
            findViewById(R.id.rl_change_time).setVisibility(View.VISIBLE);
            assignViews();
//            assignListener();
            assignLineChart();
            initialData(0);
        }
    }

    /**
     * 初始化图表控件
     */
    private void assignLineChart() {
        lineChart = (LineChart) findViewById(R.id.line_chart);
        lineChart.setOnChartGestureListener(this);
        lineChart.setOnChartValueSelectedListener(this);
        lineChart.setDrawGridBackground(false);
        //说明文字
        lineChart.setDescription("");
        // 没有数据时的说明文字
//        lineChart.setNoDataTextDescription(getString(R.string.activity_history_no_data));
        lineChart.setNoDataTextDescription(getString(R.string.loading));

        // enable value highlighting
//        lineChart.setHighlightEnabled(true);
        // enable touch gestures
        lineChart.setTouchEnabled(true);
        // enable scaling and dragging
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);
        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(true);
        //X轴 Y轴分别对应的缩放开关
        // mChart.setScaleXEnabled(true);
        // mChart.setScaleYEnabled(true);
        // set an alternative background color
        // mChart.setBackgroundColor(Color.GRAY);
        // create a custom MarkerView (extend MarkerView) and specify the layout
        // to use for it
        mv = new MyMarkerView(this, R.layout.custom_marker_view);
        // set the marker to the chart
        lineChart.setMarkerView(mv);
        //设置Y轴
        setYAxisAndLimit(30f, 20f);
        //设置X轴
        setXAxis();
        //关闭右边轴
        lineChart.getAxisRight().setEnabled(false);
//        mChart.setVisibleXRange(20);
//        mChart.setVisibleYRange(20f, AxisDependency.LEFT);
//        mChart.centerViewTo(20, 50, AxisDependency.LEFT);
        lineChart.animateX(2500, Easing.EasingOption.EaseInOutQuart);
        // get the legend (only possible after setting data)
        Legend l = lineChart.getLegend();
        String title = switchInfoText();
        String[] legends = new String[]{String.format(getString(R.string.linechart_max_legend), title), String.format(getString(R.string.linechart_avg_legend), title), String.format(getString(R.string.linechart_min_legend), title)};
        l.setCustom(new int[]{getResources().getColor(R.color.red), getResources().getColor(R.color.font_lightblue), getResources().getColor(R.color.green)}, legends);
        l.setTextColor(getResources().getColor(R.color.font_lightwhite));
        // modify the legend ...
        // l.setPosition(LegendPosition.LEFT_OF_CHART);
        l.setForm(Legend.LegendForm.LINE);
    }

    /**
     * 设置x轴
     */
    private void setXAxis() {
//        setXAxisLimit();
        XAxis bottomAxis = lineChart.getXAxis();
        bottomAxis.setTextColor(getResources().getColor(R.color.font_lightwhite));
        bottomAxis.setPosition(XAxis.XAxisPosition.BOTTOM_INSIDE);
    }

    private void setXAxisLimit() {
        // x-axis limit line
        LimitLine llXAxis = new LimitLine(10f, "Index 10");
        llXAxis.setLineWidth(4f);
        llXAxis.enableDashedLine(10f, 10f, 0f);
        llXAxis.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
        llXAxis.setTextSize(10f);
        XAxis xAxis = lineChart.getXAxis();
        xAxis.addLimitLine(llXAxis);
    }

    /**
     * 设置Y轴参数
     *
     * @param min
     * @param max
     */
    private void setYAxisAndLimit(float min, float max) {
        setYAxis(min, max);
        setYAxisLimit();
    }

    /**
     * 设置Y轴坐标
     *
     * @param min
     * @param max
     */
    private void setYAxis(float min, float max) {
        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setTextColor(getResources().getColor(R.color.font_lightwhite));
        leftAxis.setAxisMaxValue(max);
        leftAxis.setAxisMinValue(min);
        leftAxis.setValueFormatter(new YAxisValueFormatter() {

            @Override
            public String getFormattedValue(float value, YAxis yAxis) {
                String strvalue = null;
                switch (deviceBean.getFunctype()) {
                    case 100:
                        //PH
                        value = (float) (Math.round(value * 100)) / 100;
                        DecimalFormat decimalFormat = new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                        strvalue = decimalFormat.format(value);
                        break;
                    case 11:
                        //TEMPERATURE
                        BigDecimal b2 = new BigDecimal(value);
                        value = b2.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
                        strvalue = String.valueOf(value);
                        break;
                    case 101:
                        //WATERLEVER
                        value = value;
                        strvalue = String.valueOf(value);
                        break;
                    default:
                        value = value;
                        strvalue = String.valueOf(value);
                        break;
                }

                return strvalue;
            }
        });
        leftAxis.setStartAtZero(false);
        //leftAxis.setYOffset(20f);
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        // limit lines are drawn behind data (and not on top)
        leftAxis.setDrawLimitLinesBehindData(true);
    }

    /**
     * 设置Y轴的上下限
     */
    @NonNull
    private void setYAxisLimit() {
        LimitLine ll1 = setYAxisUpperLimit(130f, "Upper Limit");
        LimitLine ll2 = setYAxisLowerLimit(-30f, "Lower Limit");
        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
        leftAxis.addLimitLine(ll1);
        leftAxis.addLimitLine(ll2);
    }

    /**
     * 设置Y轴的下限
     *
     * @param limit
     * @param label
     * @return
     */
    private LimitLine setYAxisLowerLimit(float limit, String label) {
        LimitLine ll2 = new LimitLine(limit, label);
        ll2.setLineWidth(4f);
        ll2.enableDashedLine(10f, 10f, 0f);
        ll2.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
        ll2.setTextSize(10f);
        return ll2;
    }

    /**
     * 设置Y轴上限
     *
     * @param limit
     * @param label
     * @return
     */
    private LimitLine setYAxisUpperLimit(float limit, String label) {
        LimitLine ll1 = new LimitLine(limit, label);
        ll1.setLineWidth(4f);
        ll1.enableDashedLine(10f, 10f, 0f);
        ll1.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
        ll1.setTextSize(10f);
        return ll1;
    }

    /**
     * 初始化图表参数
     *
     * @param position
     */
    private void initialData(int position) {
        start = "30m";
        end = null;
        //Locale.CHINA 周一为一周的第一天
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.setTimeInMillis(System.currentTimeMillis());
        SimpleDateFormat 格式 = new SimpleDateFormat("M月d日 H时m分", Locale.CHINA);

        switch (position) {
            case 0:
                sum = "1m";
                //30min
                if (calendar.get(Calendar.MINUTE) < 30) {
                    calendar.set(Calendar.MINUTE, 0);
                } else {
                    calendar.set(Calendar.MINUTE, 30);
                }
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                start = String.valueOf(calendar.getTimeInMillis());
                end = String.valueOf(System.currentTimeMillis());
                break;
            case 1:
                //6H
                sum = "10m";
                if (calendar.get(Calendar.HOUR_OF_DAY) < 6) {
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                } else if (calendar.get(Calendar.HOUR_OF_DAY) < 12) {
                    calendar.set(Calendar.HOUR_OF_DAY, 6);
                } else if (calendar.get(Calendar.HOUR_OF_DAY) < 18) {
                    calendar.set(Calendar.HOUR_OF_DAY, 12);
                } else if (calendar.get(Calendar.HOUR_OF_DAY) >= 18) {
                    calendar.set(Calendar.HOUR_OF_DAY, 18);
                }
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                start = String.valueOf(calendar.getTimeInMillis());
                end = String.valueOf(System.currentTimeMillis());
                break;
            case 2:
                //1D
                sum = "60m";
                int average = calendar.get(Calendar.HOUR_OF_DAY);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                start = String.valueOf(calendar.getTimeInMillis());
//                calendar.set(Calendar.HOUR, 23);
//                calendar.set(Calendar.MINUTE, 59);
//                calendar.set(Calendar.SECOND, 59);
//                calendar.set(Calendar.MILLISECOND, 999);
                end = String.valueOf(System.currentTimeMillis());
                break;
            case 3:
                //1W
//                start = "1w";
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                start = String.valueOf(calendar.getTimeInMillis());
                end = String.valueOf(System.currentTimeMillis());
                sum = "1h";
                break;
        }
//        mHandler.sendEmptyMessage(LOADINGSTART);
        modeSelectior.setText(格式.format(Long.valueOf(start)), 格式.format(Long.valueOf(end)));
        if (position == 0)
            interactUtil.getOtherHistoryData(deviceBean.getDeviceid(), uid, String.valueOf(start), end, sum);
        else
            interactUtil.getOtherHistoryData(deviceBean.getDeviceid(), uid, start, end, sum);
    }

    /**
     * 初始化Toolbar
     */
    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_histoty_data));
//        toolbar.setTitle("");
//        TextView tv = (TextView) toolbar.findViewById(R.id.tv_toolbar);
//        tv.setText(boxbean.getTitle());
        setSupportActionBar(toolbar);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mDrawer.openDrawer(GravityCompat.START);
                mHandler.sendEmptyMessage(EXIT);
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        getMenuInflater().inflate(R.menu.menu_history, menu);
        menus = menu;
        switch (deviceBean.getFunctype()) {
            case DeviceConstant.FUNCTYPE_SWITCH:
            case DeviceConstant.FUNCTYPE_WATERLEVER:
            case DeviceConstant.FUNCTYPE_FEEDER:
                break;
            default:
                //图表不需要往前往后的菜单
                menus.findItem(R.id.action_previous).setVisible(false);
                menus.findItem(R.id.action_next_day).setVisible(false);
                break;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_previous:
                switch (deviceBean.getFunctype()) {
                    case DeviceConstant.FUNCTYPE_SWITCH:
                    case DeviceConstant.FUNCTYPE_WATERLEVER:
                    case DeviceConstant.FUNCTYPE_FEEDER:
                        if (caculateTime(-1, num)) {
                            if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
                                interactUtil.getSwitchHistoryData(deviceBean.getDeviceid(), uid, start, end);
                            } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
                                interactUtil.getWaterLeverHistoryData(deviceBean.getDeviceid(), uid, start, end);
                            } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER) {
                                interactUtil.getFeederHistoryData(deviceBean.getDeviceid(), uid, start, end);
                            }
                        }
                        break;
                    default:
                        if (caculatePeriodTime(-1, num)) {
                            SimpleDateFormat 格式 = new SimpleDateFormat("y年M月d日 E H时m分s秒", Locale.CHINA);
                            System.out.println("当前PeriodTimeStart时间:" + 格式.format(Long.valueOf(start)));
                            System.out.println("当前PeriodTimeEnd时间:" + 格式.format(Long.valueOf(end)));
                        }
                        interactUtil.getOtherHistoryData(deviceBean.getDeviceid(), uid, start, end, sum);
                        break;
                }

                break;
            case R.id.action_next_day:
                switch (deviceBean.getFunctype()) {
                    case DeviceConstant.FUNCTYPE_SWITCH:
                    case DeviceConstant.FUNCTYPE_WATERLEVER:
                    case DeviceConstant.FUNCTYPE_FEEDER:
                        if (caculateTime(1, num)) {
                            if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
                                interactUtil.getSwitchHistoryData(deviceBean.getDeviceid(), uid, start, end);
                            } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
                                interactUtil.getWaterLeverHistoryData(deviceBean.getDeviceid(), uid, start, end);
                            } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER) {
                                interactUtil.getFeederHistoryData(deviceBean.getDeviceid(), uid, start, end);
                            }
                        }
                        if (num == 0) {
                            showToast(getString(R.string.the_latest));
                        }
                        break;
                    default:
                        if (num == 0) {
                            showToast(getString(R.string.the_latest));
                            break;
                        }
                        if (caculatePeriodTime(1, num)) {
                            SimpleDateFormat 格式 = new SimpleDateFormat("y年M月d日 E H时m分s秒", Locale.CHINA);
                            System.out.println("当前PeriodTimeStart时间:" + 格式.format(Long.valueOf(start)));
                            System.out.println("当前PeriodTimeEnd时间:" + 格式.format(Long.valueOf(end)));
                        }
                        interactUtil.getOtherHistoryData(deviceBean.getDeviceid(), uid, start, end, sum);
                        break;
                }

                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onResume() {
        setBaseDialogContext(this);
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
        if (flag.equals(interactUtil.OTHERHISTORYDATA)) {
            //图表类数据回调
            if (ret == 0) {
                try {
                    JSONObject resultObject = ((JSONObject) object).getJSONObject("data");
                    //最大值数据
                    JSONArray maxDpsArray = resultObject.getJSONArray("max");
                    JSONObject maxDpsObject = null;
                    if (maxDpsArray.length() != 0) {
                        maxDpsObject = maxDpsArray.getJSONObject(0).getJSONObject("dps");
                    }
                    //平均值数据
                    JSONArray avgDpsArray = resultObject.getJSONArray("avg");
                    JSONObject avgDpsObject = null;
                    if (avgDpsArray.length() != 0) {
                        avgDpsObject = avgDpsArray.getJSONObject(0).getJSONObject("dps");
                    }
                    //最小值数据
                    JSONArray minDpsArray = resultObject.getJSONArray("min");
                    JSONObject minDpsObject = null;
                    if (minDpsArray.length() != 0) {
                        minDpsObject = minDpsArray.getJSONObject(0).getJSONObject("dps");
                    }
//                    JSONObject dpsObject = resultObject.getJSONObject("dps");
                    try {
                        //X轴数据
                        ArrayList<Long> xValus = sortJsonArrayByDate(maxDpsObject);
                        analysizeData(xValus, maxDpsObject, avgDpsObject, minDpsObject);
                    } catch (Exception e) {
                        ArrayList<Long> xValus = new ArrayList<>();
                        lineChart.setNoDataTextDescription(getString(R.string.activity_history_no_data));
                        analysizeData(xValus, maxDpsObject, avgDpsObject, minDpsObject);
                    }
                    mHandler.sendEmptyMessage(LOADINGOVER);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //没有数据
                lineChart.setNoDataTextDescription(getString(R.string.activity_history_no_data));
                mHandler.sendEmptyMessage(LOADINGOVER);
            }
        } else if (flag.equals(interactUtil.SWITCHHISTORYDATA)) {
            //插座类列表数据回调
            if (ret == 0) {
                try {
                    JSONArray result = (JSONArray) object;
                    switchHistoryDatas = new ArrayList<>();
                    if (result.length() != 0) {
                        oldValue = -1;
                        JSONObject resultObject = result.getJSONObject(0);
                        JSONObject dpsObject = resultObject.getJSONObject("dps");
                        SwitchHistoryData switchHistoryData;
                        Iterator iterator = dpsObject.keys();
                        while (iterator.hasNext()) {
                            switchHistoryData = new SwitchHistoryData();
                            String key = (String) iterator.next();
                            double value = dpsObject.getDouble(key) / 100;
                            switchHistoryData.setTimeStamp(key);
                            switchHistoryData.setValue(value);
                            switchHistoryDatas.add(switchHistoryData);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                排序
                Collections.sort(switchHistoryDatas, new Comparator<SwitchHistoryData>() {
                    @Override
                    public int compare(SwitchHistoryData lhs, SwitchHistoryData rhs) {
                        if (Long.valueOf(lhs.getTimeStamp()) < Long.valueOf(rhs.getTimeStamp())) {
                            return 1;
                        } else if (Long.valueOf(lhs.getTimeStamp()) > Long.valueOf(rhs.getTimeStamp())) {
                            return -1;
                        } else {
                            return 0;
                        }
                    }
                });
                //去除邻近重复数据
                for (int i = 1; i < switchHistoryDatas.size(); i++) {
                    if (switchHistoryDatas.get(i).getValue() == switchHistoryDatas.get(i - 1).getValue()) {
                        switchHistoryDatas.remove(i - 1);
                        i--;
                    }
                }
                mHandler.sendEmptyMessage(SWITCHLOADINGOVER);
            } else {
                switchHistoryDatas = new ArrayList<>();
                mHandler.sendEmptyMessage(SWITCHLOADINGOVER);
            }
        } else if (flag.equals(interactUtil.WATERLEVERHISTORYDATA)) {
            if (ret == 0) {
                try {
                    JSONArray result = (JSONArray) object;
                    switchHistoryDatas = new ArrayList<>();
                    if (result.length() != 0) {
                        oldValue = -1;
                        JSONObject resultObject = result.getJSONObject(0);
                        JSONObject dpsObject = resultObject.getJSONObject("dps");
                        SwitchHistoryData switchHistoryData;
                        Iterator iterator = dpsObject.keys();
                        while (iterator.hasNext()) {
                            String key = (String) iterator.next();
                            double value = dpsObject.getDouble(key) / 100;
                            switchHistoryData = new SwitchHistoryData();
                            switchHistoryData.setTimeStamp(key);
                            switchHistoryData.setValue(value);
                            switchHistoryDatas.add(switchHistoryData);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //水位数据排序
                Collections.sort(switchHistoryDatas, new Comparator<SwitchHistoryData>() {
                    @Override
                    public int compare(SwitchHistoryData lhs, SwitchHistoryData rhs) {
                        if (Long.valueOf(lhs.getTimeStamp()) < Long.valueOf(rhs.getTimeStamp())) {
                            return 1;
                        } else if (Long.valueOf(lhs.getTimeStamp()) > Long.valueOf(rhs.getTimeStamp())) {
                            return -1;
                        } else {
                            return 0;
                        }
                    }
                });
                //去除邻近数据
                for (int i = 1; i < switchHistoryDatas.size(); i++) {
                    if (switchHistoryDatas.get(i).getValue() == switchHistoryDatas.get(i - 1).getValue()) {
                        switchHistoryDatas.remove(i - 1);
                        i--;
                    }
                }
                mHandler.sendEmptyMessage(SWITCHLOADINGOVER);
            } else {
                switchHistoryDatas = new ArrayList<>();
                mHandler.sendEmptyMessage(SWITCHLOADINGOVER);
            }
        } else if (flag.equals(interactUtil.FEEDERHISTORYDATA)) {
            //喂食数据回调
            if (ret == 0) {
                try {
                    JSONArray result = (JSONArray) object;
                    switchHistoryDatas = new ArrayList<>();
                    if (result.length() != 0) {
                        oldValue = -1;
                        JSONObject resultObject = result.getJSONObject(0);
                        JSONObject dpsObject = resultObject.getJSONObject("dps");
                        SwitchHistoryData switchHistoryData;
                        Iterator iterator = dpsObject.keys();
                        while (iterator.hasNext()) {
                            String key = (String) iterator.next();
                            double value = dpsObject.getDouble(key) / 100;
                            if (value == 0)
                                continue;
                            switchHistoryData = new SwitchHistoryData();
                            switchHistoryData.setTimeStamp(key);
                            switchHistoryData.setValue(value);
                            switchHistoryDatas.add(switchHistoryData);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //喂食数据排序
                Collections.sort(switchHistoryDatas, new Comparator<SwitchHistoryData>() {
                    @Override
                    public int compare(SwitchHistoryData lhs, SwitchHistoryData rhs) {
                        if (Long.valueOf(lhs.getTimeStamp()) < Long.valueOf(rhs.getTimeStamp())) {
                            return 1;
                        } else if (Long.valueOf(lhs.getTimeStamp()) > Long.valueOf(rhs.getTimeStamp())) {
                            return -1;
                        } else {
                            return 0;
                        }
                    }
                });
                mHandler.sendEmptyMessage(SWITCHLOADINGOVER);
            } else {
                switchHistoryDatas = new ArrayList<>();
                mHandler.sendEmptyMessage(SWITCHLOADINGOVER);
            }
        } else {
            try {
                JSONArray result = (JSONArray) object;
                switchHistoryDatas = new ArrayList<>();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mHandler.sendEmptyMessage(SWITCHLOADINGOVER);
        }
    }

    //X轴数据处理
    private ArrayList<Long> sortJsonArrayByDate(JSONObject dpsObject) {
        ArrayList<Long> xValus = new ArrayList<Long>();
        Iterator it = dpsObject.keys();
        while (it.hasNext()) {
            String xValue = (String) it.next();
            long timestamp = Long.valueOf(xValue);
            xValus.add(timestamp);
        }
        Collections.sort(xValus, new Comparator<Long>() {
            @Override
            public int compare(Long lhs, Long rhs) {
                if (lhs < rhs) {
                    return -1;
                } else if (lhs > rhs) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        return xValus;
    }

    private void analysizeData(ArrayList<Long> xValus, JSONObject maxDpsObject, JSONObject avgDpsObject, JSONObject minDpsObject) throws JSONException {
        try {
            ArrayList<String> xValueString = new ArrayList<String>();
            ArrayList<Entry> yMaxValues = new ArrayList<>();
            ArrayList<Entry> yAvgValues = new ArrayList<>();
            ArrayList<Entry> yMinValues = new ArrayList<>();
//            if (currentPosition == 0) {
//                thirtyMinituCaculate(xValus, xAxis, maxDpsObject, avgDpsObject, minDpsObject, xValueString, yMaxValues, yAvgValues, yMinValues);
//            } else {
            DateFormat dateFormat = null;
            //X轴数据处理并计算填充
            switch (currentPosition) {
                case 0:
                    //30min
                    for (int i = 0; i < 31; i++) {
                        long xVar = Long.valueOf(start) / 1000 + i * 60;
                        dateFormat = new SimpleDateFormat("HH:mm:ss");
                        String timer = dateFormat.format(new Date(xVar * 1000));
                        xValueString.add(timer);
                    }
                    break;
                case 1:
//                    6h
                    for (int i = 0; i < 37; i++) {
                        long xVar = Long.valueOf(start) / 1000 + i * 60 * 10;
                        dateFormat = new SimpleDateFormat("HH:mm:ss");
                        String timer = dateFormat.format(new Date(xVar * 1000));
                        xValueString.add(timer);
                    }
                    break;
                case 2:
//                    1d
                    for (int i = 0; i < 25; i++) {
                        long xVar = Long.valueOf(start) / 1000 + i * 60 * 60;
                        dateFormat = new SimpleDateFormat("HH:mm:ss");
                        String timer = dateFormat.format(new Date(xVar * 1000));
                        xValueString.add(timer);
                    }
                    break;
                case 3:
//                    1w
                    for (int i = 0; i < 169; i++) {
                        long xVar = Long.valueOf(start) / 1000 + i * 60 * 60;
                        dateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");
                        String timer = dateFormat.format(new Date(xVar * 1000));
                        xValueString.add(timer);
                    }
                    break;
            }
            //Y轴数据计算处理
            for (int i = 0; i < xValus.size(); i++) {
                String xValue = String.valueOf(xValus.get(i));
                double yMin = minDpsObject.getDouble(xValue) / 100;
                double yMax = maxDpsObject.getDouble(xValue) / 100;
                double yAvg = avgDpsObject.getDouble(xValue) / 100;
                float yMinValue = Float.parseFloat(String.valueOf(yMin));
                float yMaxValue = Float.parseFloat(String.valueOf(yMax));
                float yAvgValue = Float.parseFloat(String.valueOf(yAvg));
                if (i == 0) {
                    maxValue = Math.max(yMaxValue, yAvgValue);
                    maxValue = Math.max(maxValue, yMinValue);
                    minValue = Math.min(yMaxValue, yAvgValue);
                    minValue = Math.max(minValue, yMinValue);
                } else {
                    if (maxValue < yMaxValue) {
                        maxValue = yMaxValue;
                    }
                    if (minValue > yMinValue) {
                        minValue = yMinValue;
                    }
                }
                yMinValue = switchValueType(deviceBean.getFunctype(), yMinValue);
                yMaxValue = switchValueType(deviceBean.getFunctype(), yMaxValue);
                yAvgValue = switchValueType(deviceBean.getFunctype(), yAvgValue);
                long xlongValue = xValus.get(i);
                String timer = dateFormat.format(new Date(xlongValue * 1000));
                yMinValues.add(new Entry(yMinValue, xValueString.indexOf(timer)));
                yMaxValues.add(new Entry(yMaxValue, xValueString.indexOf(timer)));
                yAvgValues.add(new Entry(yAvgValue, xValueString.indexOf(timer)));
            }
//            }
            //计算Y轴 上下padding

            switchValuePadding(deviceBean.getFunctype());
//            设置Y轴
            setYAxis(minValue, maxValue);

            /**
             * 线的颜色设置
             */
            // create a dataset and give it a type
            LineDataSet maxSet = setLineDataSet(yMaxValues);
            maxSet.setColor(getResources().getColor(R.color.red));
            LineDataSet avgSet = setLineDataSet(yAvgValues);
            avgSet.setColor(getResources().getColor(R.color.font_lightblue));
            LineDataSet minSet = setLineDataSet(yMinValues);
            minSet.setColor(getResources().getColor(R.color.green));

            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            dataSets.add(maxSet); // add the datasets
            dataSets.add(avgSet);
            dataSets.add(minSet);
            // create a data object with the datasets

            LineData data = new LineData(xValueString, dataSets);

            mv.setXValues(xValueString);
            data.setDrawValues(false);

            //如果没有数据
            if (xValueString.size() == 0) {
                lineChart.clear();
            } else {
//                System.out.println("data=" + data.toString());
                lineChart.setData(data);
//                lineChart.notifyDataSetChanged();
//                绘制
                lineChart.invalidate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void thirtyMinituCaculate(ArrayList<Long> xValus, ArrayList<Long> xAxis, JSONObject maxDpsObject, JSONObject avgDpsObject, JSONObject minDpsObject, ArrayList<String> xValueString, ArrayList<Entry> yMaxValues, ArrayList<Entry> yAvgValues, ArrayList<Entry> yMinValues) {
        try {
            int lastIndex = 0;
            long lastXAxis = 0;
            float lastMinValue = 0;
            float lastMaxValue = 0;
            float lastAvgValue = 0;
            int Index = 0;
            long nowXAxis = 0;
            if (xValus.size() == 0) {
                return;
            }
            for (int i = 0; i < xValus.size(); i++) {
                if (xValus.get(i) == Long.valueOf(start) / 1000) {
                    lastIndex = i;
                    lastXAxis = xValus.get(i);
                    Index = i + 1;
                    nowXAxis = xValus.get(i + 1);
                    double yMin = minDpsObject.getDouble(String.valueOf(lastXAxis)) / 100;
                    double yMax = maxDpsObject.getDouble(String.valueOf(lastXAxis)) / 100;
                    double yAvg = avgDpsObject.getDouble(String.valueOf(lastXAxis)) / 100;
                    float yMinValue = Float.parseFloat(String.valueOf(yMin));
                    float yMaxValue = Float.parseFloat(String.valueOf(yMax));
                    float yAvgValue = Float.parseFloat(String.valueOf(yAvg));
                    maxValue = Math.max(yMaxValue, yAvgValue);
                    maxValue = Math.max(maxValue, yMinValue);
                    minValue = Math.min(yMaxValue, yAvgValue);
                    minValue = Math.max(minValue, yMinValue);
                    lastMinValue = switchValueType(deviceBean.getFunctype(), yMinValue);
                    lastMaxValue = switchValueType(deviceBean.getFunctype(), yMaxValue);
                    lastAvgValue = switchValueType(deviceBean.getFunctype(), yAvgValue);
                    break;
                }
                if (xValus.get(i) > Long.valueOf(start) / 1000) {
                    Index = i;
                    nowXAxis = xValus.get(i);
                    if (i > 1) {
                        lastIndex = i - 1;
                        lastXAxis = xValus.get(i - 1);
                        double yMin = minDpsObject.getDouble(String.valueOf(lastXAxis)) / 100;
                        double yMax = maxDpsObject.getDouble(String.valueOf(lastXAxis)) / 100;
                        double yAvg = avgDpsObject.getDouble(String.valueOf(lastXAxis)) / 100;
                        float yMinValue = Float.parseFloat(String.valueOf(yMin));
                        float yMaxValue = Float.parseFloat(String.valueOf(yMax));
                        float yAvgValue = Float.parseFloat(String.valueOf(yAvg));
                        maxValue = Math.max(yMaxValue, yAvgValue);
                        maxValue = Math.max(maxValue, yMinValue);
                        minValue = Math.min(yMaxValue, yAvgValue);
                        minValue = Math.max(minValue, yMinValue);
                        lastMinValue = switchValueType(deviceBean.getFunctype(), yMinValue);
                        lastMaxValue = switchValueType(deviceBean.getFunctype(), yMaxValue);
                        lastAvgValue = switchValueType(deviceBean.getFunctype(), yAvgValue);
                    }
                    break;
                }
            }
            for (int j = 0; j < 31; j++) {
                if (nowXAxis == 0) {
                    lineChart.setNoDataTextDescription(getString(R.string.activity_history_no_data));
                    break;
                }
                long xVar = Long.valueOf(start) / 1000 + j * 60;
                xAxis.add(xVar);
                DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
                String timer = dateFormat.format(new Date(xVar * 1000));
                xValueString.add(timer);
                if (xVar < nowXAxis) {
                    if (lastIndex == 0 && lastXAxis == 0) {
                        continue;
                    }
                    yMinValues.add(new Entry(lastMinValue, j));
                    yMaxValues.add(new Entry(lastMaxValue, j));
                    yAvgValues.add(new Entry(lastAvgValue, j));
                } else if (xVar >= nowXAxis && lastIndex < (xValus.size() - 1)) {
                    lastIndex = lastIndex + 1;
                    lastXAxis = xValus.get(lastIndex);
                    if (Index < xValus.size() - 1) {
                        Index = Index + 1;
                        nowXAxis = xValus.get(Index);
                    }
                    double ysMin = minDpsObject.getDouble(String.valueOf(lastXAxis)) / 100;
                    double ysMax = maxDpsObject.getDouble(String.valueOf(lastXAxis)) / 100;
                    double ysAvg = avgDpsObject.getDouble(String.valueOf(lastXAxis)) / 100;
                    float ysMinValue = Float.parseFloat(String.valueOf(ysMin));
                    float ysMaxValue = Float.parseFloat(String.valueOf(ysMax));
                    float ysAvgValue = Float.parseFloat(String.valueOf(ysAvg));
                    maxValue = Math.max(ysMaxValue, ysAvgValue);
                    maxValue = Math.max(maxValue, ysMinValue);
                    minValue = Math.min(ysMaxValue, ysAvgValue);
                    minValue = Math.max(minValue, ysMinValue);
                    lastMinValue = switchValueType(deviceBean.getFunctype(), ysMinValue);
                    lastMaxValue = switchValueType(deviceBean.getFunctype(), ysMaxValue);
                    lastAvgValue = switchValueType(deviceBean.getFunctype(), ysAvgValue);
                    yMinValues.add(new Entry(lastMinValue, j));
                    yMaxValues.add(new Entry(lastMaxValue, j));
                    yAvgValues.add(new Entry(lastAvgValue, j));
                } else if (xVar >= nowXAxis && xVar <= (Long.valueOf(end) / 1000)) {
                    yMinValues.add(new Entry(lastMinValue, j));
                    yMaxValues.add(new Entry(lastMaxValue, j));
                    yAvgValues.add(new Entry(lastAvgValue, j));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //切换值
    private float switchValueType(int functype, float yValue) {
        float value = 0;
        switch (functype) {
            case 100:
                //PH
                BigDecimal b1 = new BigDecimal(yValue);
                value = b1.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                break;
            case 11:
                //TEMPERATURE
                BigDecimal b2 = new BigDecimal(yValue / 10);
                value = b2.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
                break;
            case 101:
                //WATERLEVER
                value = yValue;
                break;
            default:
                value = yValue;
                break;

        }
        return value;
    }

    /**
     * 计算Y轴
     * 上下PADDING
     *
     * @param functype
     */
    private void switchValuePadding(int functype) {
        switch (functype) {
            case 100:
                //PH
                minValue = minValue - 2;
                maxValue = maxValue + 2;
                break;
            case 11:
                //TEMPERATURE
                BigDecimal bmin = new BigDecimal(minValue / 10);
                minValue = bmin.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue() - 5.0f;
                BigDecimal bmax = new BigDecimal(maxValue / 10);
                maxValue = bmax.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue() + 5.0f;
                break;
            case 101:
                //WATERLEVER
                minValue = minValue - 1;
                maxValue = maxValue + 1;
                break;
        }
    }

    //设置点
    @NonNull
    private LineDataSet setLineDataSet(ArrayList<Entry> yVals) {
        String title = switchInfoText();
        LineDataSet set1 = new LineDataSet(yVals, title);
        // set1.setFillAlpha(110);
        // set1.setFillColor(Color.RED);
        // set the line to be drawn like this "- - - - - -"
        set1.enableDashedLine(10f, 0f, 0f);
//        set1.setColor(getResources().getColor(R.color.font_lightwhite));
        set1.setCircleColor(getResources().getColor(R.color.font_lightwhite));
        set1.setLineWidth(1f);
        set1.setCircleSize(3f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.setFillAlpha(65);
        set1.setFillColor(getResources().getColor(R.color.font_lightwhite));
        return set1;
    }

    /**
     * 设置标题
     * @return
     */
    private String switchInfoText() {
        String title = null;
        switch (deviceBean.getFunctype()) {
            case 100:
                //PH
                title = getString(R.string.activity_history_ph);
                break;
            case 11:
                title = getString(R.string.activity_history_temperature);
                //TEMPERATURE
                break;
            case 101:
                title = getString(R.string.activity_history_water_lever);
                //WATERLEVER
                break;
        }
        return title;
    }


    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartLongPressed(MotionEvent me) {

    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {

    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {

    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {

    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
        float value = e.getVal();
    }

    @Override
    public void onNothingSelected() {

    }


}
